#!/usr/bin/env python
#coding:utf-8

import os
import urllib
import urllib2,logging,json

os.sys.path.insert(0,os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import datetime


_HTTP_GET = 'GET'
_HTTP_POST = 'POST'
_HTTP_UPLOAD = 'UPLOAD'

from Crypto.Cipher import DES
from Crypto import Random
import base64
BS = DES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
unpad = lambda s : s[0:-ord(s[-1])]

class AESCipher:
    def __init__( self, key ):
        """
        Requires hex encoded param as a key
        """
        self.key = key

    def encrypt( self, raw ):
        """
        Returns hex encoded encrypted value!
        """
        raw = pad(raw)
        iv = self.key;       
        cipher = DES.new( self.key, DES.MODE_CBC, iv )
        return (cipher.encrypt( raw ) )

    def decrypt( self, enc ):
        """
        Requires hex encoded param to decrypt
        """
        iv = self.key;
        cipher = DES.new(self.key, DES.MODE_CBC, iv )
        return (cipher.decrypt(enc))

class JsonDict(dict):
    def __getattr__(self, attr):
        try:
            return self[attr]
        except KeyError:
            raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr)

    def __setattr__(self, attr, value):
        self[attr] = value

def sign_in():
    """
    论坛用户签到
    """
    key = "81b78***"
    ciphertext='phone=13520390**7&name=liusong&pid=20'
    encryptor = AESCipher(key)
    plaintext1 = base64.b64encode(encryptor.encrypt(ciphertext))    
    resp_text = _http('GET', 'http://192.168.0.245:8091/cscailogin/csai_login', \
    sign=ciphertext)
#     url='phone=13520390117'
#     print url.decode('utf-8').encode('gb2312','ignore')
#     f = urllib.urlopen("http://192.168.0.245:8091/cscailogin/csai_login",url.decode('utf-8').encode('gb2312','ignore'))
    r = _parse_json(resp_text) 
    print r 
    return 'success'
    

def _http(method, url, headers=None, **kw):
    '''
    Send http request and return response text.
    '''
    params = None
    boundary = None
    if method=='UPLOAD':
        params, boundary = _encode_multipart(**kw)
    else:
        params = _encode_params(**kw)
    http_url = '%s?%s' % (url, params) if method==_HTTP_GET else url
    http_body = None if method=='GET' else params
    logging.error('%s: %s' % (method, http_url))
    req = urllib2.Request(http_url, data=http_body)
    req.add_header('Accept-Encoding', 'gzip')
    if headers:
        for k, v in headers.iteritems():
            req.add_header(k, v)
    if boundary:
        req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
    try:
        resp = urllib2.urlopen(req, timeout=5)
        return _read_http_body(resp)
    finally:
        pass

def _read_http_body(http_obj):
    using_gzip = http_obj.headers.get('Content-Encoding', '')=='gzip'
    body = http_obj.read()
    if using_gzip:
        gzipper = gzip.GzipFile(fileobj=StringIO(body))
        fcontent = gzipper.read()
        gzipper.close()
        return fcontent
    return body



def _parse_json(s):
    '''
    Parse json string into JsonDict.

    >>> r = _parse_json(r'{"name":"Michael","score":95}')
    >>> r.name
    u'Michael'
    >>> r['score']
    95
    '''
    return json.loads(s, object_hook=lambda pairs: JsonDict(pairs.iteritems()))

def _encode_params(**kw):
    
    def _encode(L, k, v):
        if isinstance(v, unicode):
            L.append('%s=%s' % (k, urllib.quote(v.encode('utf-8'))))
        elif isinstance(v, str):
            L.append('%s=%s' % (k, urllib.quote(v)))
        elif isinstance(v, collections.Iterable):
            for x in v:
                _encode(L, k, x)
        else:
            L.append('%s=%s' % (k, urllib.quote(str(v))))
    args = []
    for k, v in kw.iteritems():
        _encode(args, k, v)
    return '&'.join(args)
if __name__ == '__main__':
    sign_in()
    exit(0)
